package com.woniuxy.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.Key;
import java.util.Date;
import java.util.Map;

@Component
public class JwtUtil {
    @Resource
    private  JwtProperties jp;

    public String create(Map<String,Object> maps,Integer time){

        Key key = Keys.hmacShaKeyFor(jp.getSecret().getBytes());
        time =time ==null?jp.getTime():time;
        JwtBuilder jb = Jwts.builder();
        if(maps!=null){
            jb.setClaims(maps);
        }
        return jb.setExpiration(new Date(System.currentTimeMillis() + time * 60 * 1000))
                .signWith(key, SignatureAlgorithm.HS256)
                .compact();
    }
    public String create(Integer time){
        return this.create(null,time);
    }

    public String create(Map<String,Object> maps){
        return this.create(maps,null);
    }

    public String create(){
        return this.create(null,null);
    }

    public Claims parse(String token){
        Key key = Keys.hmacShaKeyFor(jp.getSecret().getBytes());
        return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
    }

}
